package net.zjitc.controller;

import net.zjitc.pojo.Admin;
import net.zjitc.pojo.Category;
import net.zjitc.service.AdminService;
import net.zjitc.service.CategoryService;
import net.zjitc.utils.APIResponse;
import net.zjitc.utils.JwtUtil;
import net.zjitc.utils.Token;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("/admin")
public class AdminController {
    @Autowired
    private AdminService adminService;
    @Autowired
    private CategoryService categoryService;

//    @PostMapping("login")
    public String login(Admin admin, Model model, HttpSession session){
        Admin user=adminService.findAdmin(admin.getUsername(),admin.getPassword());
        if (user!=null){
            model.addAttribute("msg","登陆成功!");
            session.setAttribute("admin",user);
            return "redirect:/admin/list";
        }
        model.addAttribute("msg","登陆失败!");
        return "login";
    }

    @PostMapping("login")
    @ResponseBody
    public APIResponse<Token> login(@RequestBody Admin admin){
        Admin user=adminService.findAdmin(admin.getUsername(),admin.getPassword());
        APIResponse apiResponse=new APIResponse<>();
        apiResponse.setData(new Token());
        if(user!=null){
            String token= new JwtUtil().generateToken(admin.getUsername());
            apiResponse.oK("登陆成功!",new Token(token));
            return apiResponse;
        }else{
            apiResponse.error(1000,"登陆失败",null);
            return apiResponse;
        }
    }



//    @RequestMapping(value = "/list", method = RequestMethod.GET)
//    public String listUsers(Model model) {
//
//        List<Category> categories = categoryService.getAllCategories();
//        model.addAttribute("categories", categories);
//
//        return "list"; // 返回 list.jsp 页面
//    }
//    @RequestMapping(value = "/list", method = RequestMethod.POST)
//    public String SelectUsers(@RequestParam("name") String name, Model model) {
//
//        Category categories = categoryService.getCategoryById(name);
//        model.addAttribute("categories", categories);
//
//        return "list"; // 返回 list.jsp 页面
//    }
}
